package com.sinosoft.ptas.system.util;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ExportExcel<T> {

	//日期的显示格式
		private String pattern = "yyyy-MM-dd";
		
		public ExportExcel(){}
		public ExportExcel(String pattern){
			this.pattern = pattern;
		}
		/**
		 * 将数据导出到excel表格中
		 * @param data 需要导出的数据
		 * @return HSSFWorkbook
		 * @throws UnsupportedEncodingException
		 */
		public HSSFWorkbook exportExcel(List<T> data) throws UnsupportedEncodingException {
			if(data==null||data.size()<=0){
				return null;
			}
			// 声明一个工作薄
			HSSFWorkbook workbook = new HSSFWorkbook();
			//获取excel的表名,列宽
			Class<?> clazz = data.get(0).getClass();			
			Excel excel = clazz.getAnnotation(Excel.class);			
			String sheetName;
			int columnWidth;
			if(excel!=null){
				sheetName = excel.sheetName();
				columnWidth = excel.columnWidth();
				if("".equals(sheetName)){
					sheetName = "sheet1";
				}
			}else{
				sheetName = "sheet1";
				columnWidth = 30;
			}

			// 根据工作簿生成一个表格sheet对象
			HSSFSheet sheet = workbook.createSheet(sheetName);
			// 设置表格默认列宽度为15个字节
			sheet.setDefaultColumnWidth(columnWidth);
			//设置表头的样式
			HSSFCellStyle titleStyle = TitleStyle(workbook);
			//设置内容的样式
			HSSFCellStyle contentStyle = contentStyle(workbook);
			// 产生表格标题行
			generateExcelTitle(clazz, sheet, titleStyle);
			//产生数据行
			generateExcelContent(data, pattern, sheet, contentStyle);
			return workbook;
		}
		//创建表格的内容
		private void generateExcelContent(List<T> data, String pattern, 
				HSSFSheet sheet, HSSFCellStyle style2) {
			Iterator<T> it = data.iterator();
			int index = 0;
			while (it.hasNext()) {
				index++;
				HSSFRow row = sheet.createRow(index);
				T t = (T) it.next();
				// 利用反射，根据javabean属性的先后顺序，动态调用getXxx()方法得到属性值
				Class<?> c = t.getClass();
				Field[] fields = c.getDeclaredFields();
				int columNumber = 0;
				for (int i = 0; i < fields.length; i++) {
					Excel excelTitle = fields[i].getAnnotation(Excel.class);
					if (excelTitle != null) {
						HSSFCell cell = row.createCell(columNumber);
						columNumber++;
						//设置单元格样式
						cell.setCellStyle(style2);
						Field field = fields[i];
						String fieldName = field.getName();
						String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
						try {

							// 动态调用类中属性的get方法
							Method getMethod = c.getMethod(getMethodName, new Class[] {});
							Object value = getMethod.invoke(t, new Object[] {});
							if (value == null) {
								continue;
							}
							String textValue = value.toString();
							// 判断值的类型后进行强制类型转换
							// 如果不是图片数据，就利用正则表达式判断textValue是否全部由数字组成
							Pattern p = Pattern.compile("^\\d+(\\.\\d+)?$");
							Matcher matcher = p.matcher(textValue);
							if (matcher.matches()) {
								// 是数字当作double处理
								cell.setCellValue(Double.parseDouble(textValue));
							} else if (value instanceof Date) {
								Date date = (Date) value;
								SimpleDateFormat sdf = new SimpleDateFormat(pattern);
								textValue = sdf.format(date);
								cell.setCellValue(textValue);
							} else {
								cell.setCellValue(textValue);
							}
						} catch (SecurityException e) {
							e.printStackTrace();
						} catch (NoSuchMethodException e) {
							e.printStackTrace();
						} catch (IllegalArgumentException e) {
							e.printStackTrace();
						} catch (IllegalAccessException e) {
							e.printStackTrace();
						} catch (InvocationTargetException e) {
							e.printStackTrace();
						} finally {
							// 清理资源
						}
					}
				}
			}
		}
		//创建表格的表头
		private void generateExcelTitle(Class<?> clazz, HSSFSheet sheet,HSSFCellStyle style) {
			Field[] fieldsTitle = clazz.getDeclaredFields();
			HSSFRow row = sheet.createRow(0);
			row.setHeight((short) 340);
			//列数索引
			int titleColumNumber = 0;
			for (int i = 0; i < fieldsTitle.length; i++) {
				Excel excelTitle = fieldsTitle[i].getAnnotation(Excel.class);
				if (excelTitle != null) {
					String titleText = fieldsTitle[i].getAnnotation(Excel.class).titleName().trim();
					if (titleText != null && !"".equals(titleText)) {
						HSSFCell cell = row.createCell(titleColumNumber);
						// 设置表头的样式为style
						cell.setCellStyle(style);
						HSSFRichTextString text = new HSSFRichTextString(titleText);
						// 设置表头的内容
						cell.setCellValue(text);
						titleColumNumber++;
					}
				}
			}
		}
		//设置excel表格内容的样式
		private HSSFCellStyle contentStyle(HSSFWorkbook workbook) {
			HSSFCellStyle style2 = workbook.createCellStyle();
			style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
			// 生成另一个字体
			HSSFFont font2 = workbook.createFont();
			font2.setFontHeightInPoints((short) 12);
			// 把字体应用到当前的样式
			style2.setFont(font2);
			return style2;
		}
		//设置excel表格的表头样式
		private HSSFCellStyle TitleStyle(HSSFWorkbook workbook) {
			HSSFCellStyle style = workbook.createCellStyle();
			// 设置单元格中的文本的是否居中
			style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
			// 生成一个字体
			HSSFFont font = workbook.createFont();
			font.setFontHeightInPoints((short) 12);
			font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
			// 把字体应用到当前的样式
			style.setFont(font);
			return style;
		}
}
